package cn.nubia.admin.api.zuimeia.service;

import cn.nubia.admin.api.zuimeia.bean.Apps;
import cn.nubia.admin.api.zuimeia.transport.AppsReq;
import cn.nubia.admin.api.zuimeia.transport.AppsResp;
import cn.nubia.admin.file.FileManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * Created by Administrator on 2015/7/24.
 */
@Service
public class AppsService {

    private final static Logger logger = LoggerFactory.getLogger(AppsService.class);


    /**
     * 获取最美应用
     *
     * @return
     */
    public Apps getApp() throws IOException {
        return getAppByCategory(1);
    }


    /**
     * 获取最美游戏.
     *
     * @return
     */
    public Apps getGame() throws IOException {
        return getAppByCategory(2);
    }


    public AppsResp getApps(Integer pageNo, Integer pageSize) {
        AppsReq appsReq = new AppsReq("http://zuimeia.com/api/resource/nubia/", pageNo, pageSize);
        return appsReq.send();
    }

    private Apps getAppByCategory(int category) throws IOException {
        for (int i = 1; i < 100; i++) {
            AppsResp appsResp = getApps(i, 20);
            if (appsResp.getData() != null && appsResp.getData().getApps() != null) {
                for (int appIndex = 0; appIndex < appsResp.getData().getApps().size(); appIndex++) {
                    Apps app = appsResp.getData().getApps().get(i);
                    if (app.getCategory() == category) {
                        String iconImageUrl = app.getIcon_image();
                        if(iconImageUrl != null){
                            String newUrl = FileManager.uploadFile(iconImageUrl);
                            app.setIcon_image(newUrl);
                        }
                        String picUrl = app.getCover_image();
                        if(picUrl != null){
                            String newUrl = FileManager.uploadFile(picUrl);
                            app.setCover_image(newUrl);
                        }
                        return app;
                    }
                }
            }
        }
        return null;
    }
}
